//
//  HomeViewController.m
//  V-Learn
//
//  Created by Apple on 2018/12/20.
//  Copyright © 2018 yxk. All rights reserved.
//

#import "HomeViewController.h"
#import "SDCycleScrollView.h"
#import "LBZuijiaCell.h"
#import "LBShuangyuCell.h"
#import "LBOnlineVC.h"
#import "LBSaomangAreaVC.h"
#import "LBNiuAchiveVC.h"
#import "LBCoursePackageVC.h"
#import "LBHomeCoureseModel.h"
#import "LBCourseOutputDTOListModel.h"
#import "LBZhutiCell.h"
#import "LBCoureseDetailVC.h"
#import "LBZhutiCourseVC.h"
#import "LBKechengListVC.h"
#import "LBShuangyuShenqingVC.h"
//测试专属定制
#import "LBEvaluationResultVC.h"
#import "LBOnlineVC.h"
#import "WKOnlinePingguResultModel.h"
#import "WKShuangyuSuccessViewController.h"
#import "WKBannerModel.h"
#import "WKHotmenModel.h"
#import "WKHotclockInfoVOListModel.h"
#import "WKNiuwaVideoDetailVC.h"
#import "WKNiuwaTuwenVC.h"
#import "RCReloadView.h"
@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,LBShuangyuCellDelegate,LBZhutiCellDelegate,SDCycleScrollViewDelegate,LBZuijiaCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) NSArray *dataArray;/**列表数组  双语课程、主题课程*/
@property (nonatomic, strong) NSMutableArray *shuangyuCoureseArray;/**双语课程数组*/
@property (nonatomic, strong) NSMutableArray *zhutiCourseArray;/**主题课程数组*/
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong) NSString *zhutiCateId;//区分主题课  双语课程 的更多
@property (nonatomic, strong) NSString *shuangyuCateId;//区分主题课  双语课程 的更多
@property (nonatomic, strong) NSMutableArray *tempArray;
@property (nonatomic, strong) NSMutableArray *bannerArray;//轮播数组
@property (nonatomic, strong) UIButton *moreBtn;//
@property (nonatomic, strong) NSArray *onLineDataArray;//

@property (nonatomic, strong) NSMutableArray *optimumArray;//当日最佳数组
@property (nonatomic, strong) RCReloadView *reloadView;
@property (nonatomic, strong) AFNetworkReachabilityManager *manager;

@end

@implementation HomeViewController

{
    NSArray *_imagesURLStrings;
}
- (NSMutableArray *)optimumArray{
    if (!_optimumArray) {
        _optimumArray = [NSMutableArray array];
    }
    return _optimumArray;
}
- (NSMutableArray *)bannerArray{
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -LBHeight_StatusBar, ScreenW, ScreenH-LBHeight_TabBar+LBHeight_StatusBar) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
    
}
- (NSMutableArray *)zhutiCourseArray{
    if (!_zhutiCourseArray) {
        _zhutiCourseArray = [NSMutableArray array];
    }
    return _zhutiCourseArray;
}
- (NSMutableArray *)shuangyuCoureseArray{
    if (!_shuangyuCoureseArray) {
        _shuangyuCoureseArray = [NSMutableArray array];
    }
    return _shuangyuCoureseArray;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self setupUI];
//    [self requestData];
//    [self requestBannerData];
//
    // 1.获得网络监控的管理者
   self.manager  = [AFNetworkReachabilityManager sharedManager];
//    [manager stopMonitoring];
    // 2.设置网络状态改变后的处理
    __weak typeof(self)weakSelf = self;
    [self.manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                [weakSelf requestAllData];
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            
                [weakSelf requestAllData];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
//                NSLog(@"手机自带网络");
                [weakSelf requestAllData];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
//                NSLog(@"WIFI");
                [weakSelf requestAllData];
                break;
        }
    }];
    
    // 3.开始监控
    [self.manager startMonitoring];
    
}
- (void)dealloc{
    [self.manager stopMonitoring];
}
- (void)requestAllData{
    
    [self requestData];
    [self requestBannerData];
    //当日最佳
    [self requestTodayGoodData];

    
}
- (void)requestTodayGoodData{
    NSString *token = [UserModel getUserModel].token;
    NSMutableDictionary *data=[NSMutableDictionary dictionary];
    if (token) {
        [data setObject:token forKey:@"canNullToken"];
    }else{
        
    }
    [WYHXNetWorkManager get:WKQueryCurrentBest_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            //关闭网络监测
            [self.manager stopMonitoring];
            NSArray *data = responseObj[@"data"];
            self.optimumArray = [WKHotmenModel mj_objectArrayWithKeyValuesArray:data];
        }
        [self.tableView reloadData];
    }];
}
#pragma mark - 轮播数据
- (void)requestBannerData{
    [WYHXNetWorkManager get:WKQueryBanner_WKURL params:@{} completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            //网络监测关闭
            [self.manager stopMonitoring];
          NSArray *arr = [WKBannerModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
            for (int i=0; i<arr.count; i++) {
                WKBannerModel *model = arr[i];
                NSString *url = [NSString stringWithFormat:@"%@%@",Public_URL,model.bannerImage];
                [self.bannerArray addObject:url];
            }
            self.cycleScrollView.imageURLStringsGroup = self.bannerArray;
        }
        [self.tableView reloadData];
    }];
}
#pragma mark - 创建子控件
- (void)setupUI{
    self.navigationItem.title = @"首页";
    self.view.backgroundColor = [UIColor whiteColor];
    
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, ScreenW, 224) delegate:self placeholderImage:[UIImage imageNamed:@"home_bg"]];
    
    _cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleNone;
    self.headerView = [UIView new];
    self.headerView.frame = CGRectMake(0, 0, ScreenW, 294);
    [self.headerView addSubview:_cycleScrollView];
    //添加顶部视图 使用滚动视频，在iphone8上间距不合适
//    UIImageView *imageView = [[UIImageView alloc] init];
//    imageView.image = [UIImage imageNamed:@"home_bg"];
//    imageView.frame = CGRectMake(0, 0, ScreenW, 224);
//    [self.headerView addSubview:imageView];
    
    UIView *sectionView = [UIView new];
    sectionView.backgroundColor = rgb(242,242,242);
    [self.headerView addSubview:sectionView];
    [sectionView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(10);
    }];
    UIView *bottomView = [UIView new];
    bottomView.frame = CGRectMake(0, 294, ScreenW, 70);

    [self.headerView addSubview:bottomView];
    
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = [UIView new];
    UIView *smallView = [UIView new];
    smallView.backgroundColor = [UIColor whiteColor];
    smallView.layer.cornerRadius = 8;
    //如果 为ture 阴影想过出不来
    smallView.layer.masksToBounds = false;
    
    
    [self.headerView addSubview:smallView];
    
    [self addShadowToView:smallView withColor:rgba(233,84,18,0.2)];
    [smallView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.cycleScrollView.mas_bottom).mas_equalTo(-20);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(70);
    }];
    for (int i=0; i<5; i++) {
        UIView *everyView = [UIView new];
        CGFloat w = (ScreenW-15*2)/5;
        everyView.frame = CGRectMake(i*w, 0, w, 70);
        [smallView addSubview:everyView];
        NSArray *images = @[@"zxhg2",@"wk_sysq",@"wk_nwda",@"wk_smq",@"wk_kcb"];
        NSArray *titles = @[@"在线评估",@"双语申请",@"牛蛙档案",@"扫盲区",@"课程包"];
        UIButton *smallButton = [[UIButton alloc] init];
        [everyView addSubview:smallButton];
        [smallButton setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
        [smallButton setTitle:titles[i] forState:UIControlStateNormal];
        [smallButton setTitleColor:rgb(51,51,51) forState:UIControlStateNormal];
        smallButton.titleLabel.font = LBFont(12);
        smallButton.frame = CGRectMake(0, 0, w, 70);
        smallButton.tag = 100+i;
        smallButton.layer.masksToBounds = false;
        smallButton.layer.cornerRadius = 1;
        [self addShadowToView:smallButton withColor:rgba(233,84,18,0.2)];
        [smallButton addTarget:self action:@selector(clickHomeItemBtn:) forControlEvents:UIControlEventTouchUpInside];
        [smallButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -25, -35, 0)];
        [smallButton setImageEdgeInsets:UIEdgeInsetsMake(0, 20*kScaleFit, 20*kScaleFit, 0)];
        if (i==4) {
            [smallButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -35, -35, 0)];
        }
    }

    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];

}
#pragma mark - 首页顶部 添加四边阴影效果
- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    // 阴影颜色1
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移，默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度，默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    theView.layer.shadowRadius = 5;
    
}
#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    
}
#pragma mark - ListData
- (void)requestData{
    [WYHXNetWorkManager get:WKHomeList_WKURL params:nil completionHandler:^(id responseObj, NSError *error) {
        NSDictionary *dict = (NSDictionary *)responseObj;
        NSString *code = dict[@"code"];

        if ([code integerValue]==200) {
            //关闭网络监测
            [self.manager stopMonitoring];
            NSArray *data = dict[@"data"];
            self.dataArray = [LBHomeCoureseModel mj_objectArrayWithKeyValuesArray:data];

            [self.tableView reloadData];
        }
    }];
    
}
#pragma clickLBZuijiaCellButton
- (void)clickLBZuijiaCellButton:(NSInteger)index WithArray:(NSMutableArray *)dataArray{
    
    WKHotmenModel *model = [dataArray objectAtIndex:index];
    if ([model.fileType isEqualToString:@"1"]) {
        WKNiuwaVideoDetailVC *videoVC = [[WKNiuwaVideoDetailVC alloc] init];
        videoVC.nameTitle = model.username;
        videoVC.model = model;
        [self.navigationController pushViewController:videoVC animated:YES];
    }else{
        WKNiuwaTuwenVC *imageTextVC = [[WKNiuwaTuwenVC alloc] init];
        imageTextVC.nameTitle = model.username;
        imageTextVC.model = model;
        [self.navigationController pushViewController:imageTextVC animated:YES];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataArray.count+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        if (indexPath.section==0) {
            LBZuijiaCell *cell = [LBZuijiaCell cellWithTableView:tableView];
            
            cell.delegate = self;
        
            cell.dataArray = self.optimumArray;
            return cell;
        }else{
            LBHomeCoureseModel *model = [self.dataArray objectAtIndex:indexPath.section-1];
            LBShuangyuCell*cell = [LBShuangyuCell cellWithTableView:tableView];
            cell.dataArray = model.courseOutputDTOList;
            cell.delegate = self;
            return cell;
        }

}
- (void)clickCourseBtn:(UIButton *)sender{
//    NSLog(@"%ld",sender.tag);
}

#pragma mark - 双语工程按钮点击事件
- (void)clilkLBShuangyuCellBtn:(UIButton *)sender WithArray:(NSArray *)dataArray{
    NSInteger index = sender.tag - 666;
    LBCourseOutputDTOListModel *model = [dataArray objectAtIndex:index];
    LBCoureseDetailVC *courseDetailVC = [[LBCoureseDetailVC alloc] init];
    if (model.courseId==nil) {
        return;
    }
    courseDetailVC.courseId = model.courseId;
    courseDetailVC.type = model.courseType;
//    courseDetailVC.courseInfo = model.courseInfo;
    [self.navigationController pushViewController:courseDetailVC animated:YES];
    
}

#pragma mark - 在线规划
- (void)onLinePlan:(NSString*)token{

    __weak typeof(self)weakSelf = self;

        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setObject:token forKey:@"token"];
        [WYHXNetWorkManager get:WKOnLinePlan_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==202) {
                //没有规划跳转规划 页面
                LBOnlineVC *onlineVC = [LBOnlineVC new];
//                onlineVC.isVip = self.personInfoModel.isVip;
                [weakSelf.navigationController pushViewController:onlineVC animated:YES];
            }else if([code integerValue]==200){
                self.onLineDataArray  = [WKOnlinePingguResultModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
                
#warning message - 这里传递的数据到后面 重新规划， 规划成功需要重新 把这个接口重新加载一下
                LBEvaluationResultVC *onlineVC = [[LBEvaluationResultVC alloc] init];
                onlineVC.dataArray = self.onLineDataArray;
//                onlineVC.isVip = self.personInfoModel.isVip;
                [self.navigationController pushViewController:onlineVC animated:YES];
            }else if([code integerValue]==401){
                //            [self jumpLloginviewController];
                [UserModel clearUserInfo];
            }
        }];


//    }
    
    
}
- (void)jumpLloginviewController{
    LBLoginVC *loginVC = [[LBLoginVC alloc] init];
    loginVC.jumpType = @"1";
    [self.navigationController pushViewController:loginVC animated:YES];
}
#pragma mark - 点击首页顶部5个图标
- (void)clickHomeItemBtn:(UIButton *)sender{
    NSInteger index = sender.tag-100;
    switch (index) {
        case 0:
        {
            NSString *token = [UserModel getUserModel].token;
            if (!token) {
                [self jumpLloginviewController];
            }else{
                //在线规划
                [self onLinePlan:token];
            }

        }
            break;
        case 1:
        {
            NSString *token = [UserModel getUserModel].token;
            if (!token) {
                [self jumpLloginviewController];
            }else{
                //双语申请
                LBShuangyuShenqingVC *shuangyuVC = [[LBShuangyuShenqingVC alloc] init];
                [self.navigationController pushViewController:shuangyuVC animated:YES];
            }

        }
            break;
        case 2:
        {
            NSString *token = [UserModel getUserModel].token;
            if (!token) {
                [self jumpLloginviewController];
            }else{
                LBNiuAchiveVC *saomangVC = [LBNiuAchiveVC new];
                [self.navigationController pushViewController:saomangVC animated:YES];
            }
            break;
        }
        case 3:
        {
            LBSaomangAreaVC *saomangVC = [LBSaomangAreaVC new];
            [self.navigationController pushViewController:saomangVC animated:YES];
            break;
        }
        case 4:
        {
            LBCoursePackageVC *saomangVC = [LBCoursePackageVC new];
            [self.navigationController pushViewController:saomangVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}
- (void)clickEveryBtn:(UIButton *)sender{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        if (self.optimumArray.count==0) {
            return 0;
        }else{
            return 133;
        }
    }
    return 133;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [UIView new];

    UIImageView *icon = [[UIImageView alloc] init];
    [headerView addSubview:icon];
    [icon makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.size.mas_equalTo(CGSizeMake(20, 22));
        make.centerY.mas_equalTo(headerView);
    }];
    
    UILabel *titleLab = [UILabel labelWithText:@"" andTextColor:rgb(51,51,51) andName:nil andFontSize:16];
    [headerView addSubview:titleLab];
    [titleLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(icon.mas_right).mas_equalTo(9);
        make.centerY.mas_equalTo(headerView);
    }];


    LBButton *moreBtn = [LBButton buttonWithCoutomType:YFUIButtonTypeImageRight];
    moreBtn.titleLabel.font = LBFont(13);
    [moreBtn setTitle:@"更多" forState:UIControlStateNormal];
    [moreBtn setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];
    [moreBtn setImage:LBImage(@"home_right_arrow") forState:UIControlStateNormal];
    [headerView addSubview:moreBtn];
    [moreBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.size.mas_equalTo(CGSizeMake(40, 30));
        make.centerY.mas_equalTo(headerView);
        
    }];
    moreBtn.tag = 246+section;

    
        if (section==0) {
            icon.image = [UIImage imageNamed:@"home_section_drzj"];
            titleLab.text = @"当日最佳";
            moreBtn.hidden = YES;
        }else{
            moreBtn.hidden = NO;
            LBHomeCoureseModel *model = self.dataArray[section-1];
            NSString *urlString = [NSString stringWithFormat:@"%@%@",Public_URL,model.cateImage];
            
            [icon sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"home_section_sygc"]];
            titleLab.text = model.cateName;
            
    }

    self.moreBtn = moreBtn;
        [moreBtn addTarget:self action:@selector(clickHomeSecionMoreBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    return headerView;
}
#pragma mark - 点击组头更多按钮
- (void)clickHomeSecionMoreBtn:(UIButton *)sender{
    NSInteger index = sender.tag-246;
    LBHomeCoureseModel *model = self.dataArray[index-1];
            if (model.cateId.length==0||!model.cateId) {
                return;
            }
    if (model.moreType == 2) {
        LBZhutiCourseVC *VC = [LBZhutiCourseVC new];
        VC.cateId = model.cateId;
        VC.titleString = model.cateName;
        [self.navigationController pushViewController:VC animated:YES];
    }else{
        LBKechengListVC *VC = [LBKechengListVC new];
        VC.cateId = model.cateId;
        VC.titleString = model.cateName;
        [self.navigationController pushViewController:VC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [UIView new];
    footerView.backgroundColor = rgb(242,242,242);
    return footerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
@end
